package com.htx.zqs.blesmartmask.ui.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.google.gson.Gson;
import com.htx.zqs.blesmartmask.MyApplication;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.adapter.HomeListAdapter;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.bean.Courses;
import com.htx.zqs.blesmartmask.bean.CoursesData;
import com.htx.zqs.blesmartmask.bean.EventBean;
import com.htx.zqs.blesmartmask.listeners.OkListener;
import com.htx.zqs.blesmartmask.ui.activity.MainActivity;
import com.htx.zqs.blesmartmask.ui.activity.StartCourseActivity;
import com.htx.zqs.blesmartmask.ui.activity.TestWaterActivity;
import com.htx.zqs.blesmartmask.utils.AlertUtils;
import com.htx.zqs.blesmartmask.utils.BlEUtile;
import com.htx.zqs.blesmartmask.utils.BleUtils;
import com.htx.zqs.blesmartmask.utils.Constants;
import com.htx.zqs.blesmartmask.utils.EventBusUtil;
import com.htx.zqs.blesmartmask.utils.LocationUtil;
import com.htx.zqs.blesmartmask.utils.MySpUtils;
import com.htx.zqs.blesmartmask.utils.OkhttpUtils;
import com.htx.zqs.blesmartmask.utils.SPUtil;
import com.htx.zqs.blesmartmask.utils.Utils;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * Created by zhao on 2018/5/11.
 */

public class HomeFragment extends BaseFragment implements AdapterView.OnItemClickListener {

    private static final String CL_LINK = "cL.link";
    @InjectView(R.id.home_top_img)
    ImageView homeTopImg;
    @InjectView(R.id.home_center_left_img)
    ImageView homeCenterLeftImg;
    @InjectView(R.id.course_list_view)
    ListView courseListView;
    @InjectView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @InjectView(R.id.home_center_right_img)
    ImageView homeCenterRightImg;
    @InjectView(R.id.home_buttom_img)
    ImageView homeButtomImg;
    @InjectView(R.id.testButton)
    Button testButton;
    @InjectView(R.id.startButton)
    Button startButton;
    private ArrayList<Courses> courses = new ArrayList();
    private HomeListAdapter homeListAdapter;
    private KProgressHUD kProgressHUD;
    private String deviceId;

    private String mLastCourseName;
    private int mLimitCourseCount;
    private AlertDialog.Builder builder;
    private LocalBroadcastManager broadcastManager;
    private OkhttpUtils mMCourseDataOk;
    public Activity activity;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.inject(this, view);
        activity = getActivity();
        initView();
        initBroadcastRevicer();
        return view;
    }

    private void initBroadcastRevicer() {

//注册广播
        registerReceiver();

    }

    /**
     * 注册广播接收器
     */
    private void registerReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("jerry");
        broadcastManager.registerReceiver(mAdDownLoadReceiver, intentFilter);
    }

    private BroadcastReceiver mAdDownLoadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
//            String change = intent.getStringExtra("change");
//            mLastCourseName = intent.getStringExtra("mLastCourseName");
//            if ("yes".equals(change)) {
//                // 这地方只能在主线程中刷新UI,子线程中无效，因此用Handler来实现
//                new Handler().post(new Runnable() {
//                    public void run() {
//                        //在这里来写你需要刷新的地方
//                        //例如：testView.setText("恭喜你成功了");
//                        changeListView();
//                    }
//                });
//            }
        }
    };

    @Override
    public void onDetach() {
        super.onDetach();
        broadcastManager.unregisterReceiver(mAdDownLoadReceiver);
    }


    private void initView() {
        deviceId = LocationUtil.getUniquePsuedoID();
        builder = new AlertDialog.Builder(getContext());
        builder.setCancelable(false);//调用这个方法时，按对话框以外的地方不起作用。按返回键也不起作用
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // getCourseData(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);
                //getCourseDataFromALY();
                showCourse();
            }
        });
        homeListAdapter = new HomeListAdapter(getActivity());
        courseListView.setAdapter(homeListAdapter);
        courseListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        courseListView.setOnItemClickListener(this);
        homeListAdapter.setOncheckChanged(new HomeListAdapter.OnMyCheckChangedListener() {
            @Override
            public void setSelectID(int selectID) {
                homeListAdapter.setSelectID(selectID);
                //    payType = selectID;
                homeListAdapter.notifyDataSetChanged();
            }
        });
        swipeRefreshLayout.setRefreshing(false);
        kProgressHUD = BlEUtile.getmKProgressHUD(getActivity());

        // sp = getActivity().getSharedPreferences("aaaa", Context.MODE_MULTI_PROCESS);
        if (kProgressHUD != null) {
            kProgressHUD.show();
        }

        //  getCourseData(BmobQuery.CachePolicy.CACHE_ELSE_NETWORK);
        //  getCourseDataFromALY();
        showCourse();
        kProgressHUD.dismiss();
    }


    public int getCourseindex(int index) {
        if (courses == null || courses.size() == 0) {
            return 0;
        } else {
            for (int i = 0; i < courses.size(); i++) {
                if (courses.get(i).getId() == index) {
                    return i;
                }
            }
        }
        return 0;
    }

    @Override
    public void onResume() {
        super.onResume();
//        if (MyApplication.bluetoothState == 0 && MyApplication.selectCourse != null) {
//            homeListAdapter.setSelectID(getCourseindex(MyApplication.selectCourse.getId()));
//
//        } else if (MyApplication.bluetoothState != 0) {
//            homeListAdapter.setSelectID(getCourseindex(MyApplication.runningIndex));
//        }
//        homeListAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.testButton, R.id.startButton})
    public void onViewClicked(View view) {
        final BleDevice bleDevice = Utils.getFirstDevice();
        if (bleDevice != null) {
            switch (view.getId()) {
                case R.id.testButton:
                    //测试油水
                    TestWaterActivity.startAct(activity,bleDevice);
                    break;
                case R.id.startButton:
                    try {
                        String name = (String) SPUtil.get(getActivity(), deviceId, "", "mLastCourseName");
                        if (name.equals("")) {
                            mLastCourseName = "";
                        } else {
                            mLastCourseName = MyApplication.getCourseFromIndex(Integer.parseInt(name));
                        }
                    } catch (Exception e) {
                        mLastCourseName = (String) SPUtil.get(getActivity(), deviceId, "", "mLastCourseName");
                    }
                    mLimitCourseCount = (int) SPUtil.get(getContext(), deviceId, 0, "LimitCourseCount");


                    if (!MyApplication.isCourseExist) {
                        new AlertDialog.Builder(getContext()).setTitle(R.string.course_data_no_exit_title)
                                .setMessage(R.string.course_data_no_exit_message)
                                .setPositiveButton(R.string.ok, null)
                                .show();
                    } else {
                        startCourse(bleDevice);
                    }

                    break;
            }
        } else {
            ((MainActivity) getActivity()).goToBluetooth();
        }
    }

    private void changeListView() {
        for (Courses course : courses) {
            if (course.getName().equals(mLastCourseName)) {
                homeListAdapter.setSelectID(getCourseindex(course.getId()));
                homeListAdapter.notifyDataSetChanged();
                Log.e("ceshi", "startCourse: " + MyApplication.selectCourse);
                return;
            }
        }

    }

    private void startCourse(final BleDevice bleDevice) {
        if (MyApplication.bluetoothState == Contants.STATE_NO_RUN) {
            if (MyApplication.isTestWater) {
                StartCourseActivity.startAct(activity, bleDevice);
            } else {
                new AlertDialog.Builder(getContext()).setTitle(R.string.start_dialog_title)
                        .setMessage(R.string.start_dialog_message)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent1 = new Intent(getContext(), TestWaterActivity.class);
                                startActivityForResult(intent1, 10);
                            }
                        })
                        .show();
            }
        } else if (MyApplication.selectCourse.equals(MyApplication.runningCourse)) {
            StartCourseActivity.startAct(activity, bleDevice);
        } else {
            new AlertDialog.Builder(getContext()).setTitle(R.string.other_course_run_title)
                    .setMessage(R.string.other_course_run_message)
                    .setNegativeButton(R.string.other_course_run_negative_btn, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            MyApplication.isTestWater = true;
                            StartCourseActivity.startAct(activity, bleDevice);
                        }
                    })
                    .setPositiveButton(R.string.other_course_run_positive_btn, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Log.e("ceshi", "startCourse: " + MyApplication.selectCourse);
                            startNewCourse();
                        }
                    })
                    .show();
        }
    }

    private void startNewCourse() {
        //先停止 正在运行的课程
        if (MyApplication.isTestWater) {
            bleStopCourse();
        } else {
            new AlertDialog.Builder(getContext()).setTitle(R.string.start_dialog_title)
                    .setMessage(R.string.start_dialog_message)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent1 = new Intent(getContext(), TestWaterActivity.class);
                            getActivity().startActivityForResult(intent1, 10);
                        }
                    })
                    .show();
        }
    }
    private void bleStopCourse() {
        MySpUtils.putBoolean(MySpUtils.KEY_STAR_AUTO_INCREMENT, false);
        EventBusUtil.sendEvent(new EventBean(Constants.EVENT_STOP_COURSE));
        for (final BleDevice bleDevice : BleManager.getInstance().getAllConnectedDevice()) {
            BleUtils.write(bleDevice, BleUtils.getStopCourseCommand(), new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    StartCourseActivity.startAct(activity, bleDevice);
                }

                @Override
                public void onWriteFailure(BleException exception) {

                }
            });
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 10) {
            mLimitCourseCount = (int) SPUtil.get(MyApplication.appContext, deviceId, 0, "LimitCourseCount");
            if (mLimitCourseCount % 6 == 0 && MyApplication.isConnected && MyApplication.state == 0) {
                Toast.makeText(MyApplication.appContext, getResources().getString(R.string.start_course_choose), Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == 11) {
            Log.e("home", "onActivityResult: 你走这里了吗");

        } else if (requestCode == Contants.CAMERA_REQUEST_CODE) {
            if (requestCode == -1) {
                //照相成功   -1
            } else {
                //照相失败
            }
        }
//        else if (requestCode == Contants.AFTER_TEST_WATER_DATA){
//
//        }
    }

    private OkListener mOkListener = new OkListener() {
        @Override
        public void onSuccess(int requestCode, String string) {
            if (kProgressHUD != null) {
                kProgressHUD.dismiss();
            }
            if (swipeRefreshLayout != null) {
                swipeRefreshLayout.setRefreshing(false);
            }
            Log.e("==369==", string);
            SPUtil.put(getContext(), "course", string, "course");
            showCourseFromAly(string);
        }

        @Override
        public void onError(int requestCode, IOException e) {
            if (kProgressHUD != null) {
                kProgressHUD.dismiss();
            }
            if (swipeRefreshLayout != null) {
                swipeRefreshLayout.setRefreshing(false);
            }
            new AlertDialog.Builder(getContext()).setTitle(R.string.limit_course_fail_title)
                    //.setMessage(e.getLocalizedMessage())
                    .setMessage(R.string.limit_course_fail_message)
                    .setNegativeButton(R.string.cancle, null)
                    .setPositiveButton(R.string.limit_course_fail_positive, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            swipeRefreshLayout.setRefreshing(true);
                            getCourseDataFromALY();
                        }
                    })
                    .show();
        }
    };

    private void showCourseFromAly(String string) {
        Gson gson = new Gson();
        CoursesData coursesData = gson.fromJson(string, CoursesData.class);
        ArrayList<Courses> courseList = coursesData.getData();
        Log.e("home", "done: " + courseList);
        courses.clear();
        courses.addAll(courseList);
        MyApplication.courses = courses;
        homeListAdapter.setData(courses);
        Log.e("home", "done: " + courses);
        MyApplication.isCourseExist = true;
    }

    private void showCourse() {
        courses.clear();
        Courses courses1 = setCourseData(117, "true", getResources().getString(R.string.course_name_1), 50,
                5, 15, 0, "zh-CN", 995, "B");
        Courses courses2 = setCourseData(119, "true", getResources().getString(R.string.course_name_2), 50,
                5, 15, 0, "zh-CN", 89, "C");
        Courses courses3 = setCourseData(120, "true", getResources().getString(R.string.course_name_3), 50,
                5, 15, 0, "zh-CN", 4989, "D");
        Courses courses4 = setCourseData(121, "true", getResources().getString(R.string.course_name_4), 33,
                0, 10, 10, "zh-CN", 898, "E");
        Courses courses5 = setCourseData(122, "true", getResources().getString(R.string.course_name_5), 10,
                5, 10, 5, "zh-CN", 4990, "F");
        this.courses.add(courses1);
        this.courses.add(courses2);
        this.courses.add(courses3);
        this.courses.add(courses4);
        this.courses.add(courses5);
        MyApplication.courses = this.courses;
        homeListAdapter.setData(this.courses);
        Log.e("home", "done: " + this.courses);
        MyApplication.isCourseExist = true;
        swipeRefreshLayout.setRefreshing(false);
    }

    private Courses setCourseData(int id, String aTrue, String name, int percentage, int timeone,
                                  int timetwo, int timethree, String language, int frequency, String
                                          coursedate) {
        Courses course = new Courses();
        course.setId(id);
        course.setIsdefault(aTrue);
        course.setName(name);
        course.setPercentage(percentage);
        course.setTimeone(timeone);
        course.setTimetwo(timetwo);
        course.setTimethree(timethree);
        course.setLanguage(language);
        course.setFrequency(frequency);
        course.setCoursedate(coursedate);
        return course;
    }

    private HashMap mMap = new HashMap();

    private void getCourseDataFromALY() {
        if (BlEUtile.isNetworkConnected(getContext())) {
            if (mMCourseDataOk == null) {
                mMCourseDataOk = new OkhttpUtils(getActivity(), Contants.GET_COURSE_DATA_FROM_ALY, mOkListener);
            }
            mMap.clear();
            mMap.put("language", BlEUtile.getLanguage());
            mMap.put("isdefault", true);
            mMCourseDataOk.postForm(Contants.GET_COURSE_DATA_FROM_ALY, Contants.BASE_URL + CL_LINK, mMap);
        } else {
            if (kProgressHUD != null) {
                kProgressHUD.dismiss();
            }
            if (swipeRefreshLayout != null) {
                swipeRefreshLayout.setRefreshing(false);
            }
            String string = (String) SPUtil.get(getContext(), "course", "", "course");
            if (string != "") {
                showCourseFromAly(string);
            } else {
                Toast.makeText(getContext().getApplicationContext(), getResources().getString(R.string.limit_net_fail_message1), Toast.LENGTH_SHORT).show();
            }
        }
    }


    private void getCourseData(BmobQuery.CachePolicy cacheElseNetwork) {
        BmobQuery<Courses> query = new BmobQuery<Courses>();
        query.addWhereEqualTo("isDefault", true);
        String curentlanguage = BlEUtile.getLanguage();
        query.addWhereEqualTo("language", curentlanguage);
        final boolean b = query.hasCachedResult(Courses.class);
        query.setCachePolicy(cacheElseNetwork);
        query.findObjects(new FindListener<Courses>() {
            @Override
            public void done(List<Courses> list, BmobException e) {
                if (kProgressHUD != null) {
                    kProgressHUD.dismiss();
                }
                if (swipeRefreshLayout != null) {
                    swipeRefreshLayout.setRefreshing(false);
                    if (e == null) {
                        courses.clear();
                        courses.addAll(new ArrayList(list));
                        MyApplication.courses = courses;
                        homeListAdapter.setData(courses);
                        Log.e("home", "done: " + courses);
                        MyApplication.isCourseExist = true;
                    } else {
                        if (!b) {
                            new AlertDialog.Builder(getContext()).setTitle(R.string.limit_course_fail_title)
                                    //.setMessage(e.getLocalizedMessage())
                                    .setMessage(R.string.limit_course_fail_message)
                                    .setNegativeButton(R.string.cancle, null)
                                    .setPositiveButton(R.string.limit_course_fail_positive, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            swipeRefreshLayout.setRefreshing(true);
                                            HomeFragment.this.getCourseData(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);
                                        }
                                    })
                                    .show();
                        }
                    }
                }
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BlEUtile.setNull();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        homeListAdapter.setSelectID(position);
        homeListAdapter.notifyDataSetChanged();
    }
}
